package com.bbcare.nutritious.plat.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.JsonToEnetityUtil;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ExcelUtil.ExcelUtil.ExcelExportData;
import com.bbcare.comm.ExcelUtil.FileDownloadUtils;
import com.bbcare.cp.plat.store.ibatis.cp.IFollowQueueDAO;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.entity.PtCourseBespeak;
import com.bbcare.nutritious.plat.entity.PtCourseInfo;
import com.bbcare.nutritious.plat.entity.PtWeight;
import com.bbcare.nutritious.plat.service.ICourseService;
import com.bbcare.nutritious.plat.service.IWeightService;

/**
 * 课程控制器
 */
@Controller
@RequestMapping("/webapi/service/course")
public class CourseController {
	
    public static final Logger logger = Logger.getLogger(CourseController.class);
    
    @Autowired
    private ICourseService courseService;
    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;
    @Autowired
	IPatientDAO patientdao;
    @Autowired
    private IPatientTaskDAO patientTaskDao;
    @Autowired
    private IPatientService patientService;
    @Autowired
    com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO followQueueDAO;
    /**
     * app预约首页接口
     * 查询近四天的课程
     * 查询当前年的所有课程
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/getCourseBespeakIndex")
    public ResultModel<Object> getCourseBespeakIndex(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getCourseBespeakIndex----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);
        //判空
        if(StringUtils.isEmpty(courseInfo.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"患者ID不能为空");
        }
        if(courseInfo.getCurPage()<1){
        	logger.debug("分页页码小于1");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"分页页码不能小于1");
        }
        //计算分页参数
        courseInfo.setStartNum((courseInfo.getCurPage()-1)*courseInfo.getPageSize());
        Map<String,Object> rspMap = courseService.getCourseBespeakIndex(courseInfo);
        logger.debug("out getCourseBespeakIndex----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    
    /**
     * 通过id查询课程信息
     * @param request
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/getCourseInfoById")
    public ResultModel<Object> getCourseInfoById(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getCourseInfoById----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseInfo courseInfo = (PtCourseInfo) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseInfo.class);
        //判空
        if(courseInfo.getId()<=0){
        	logger.debug("out id----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"课程不能为空");
        }
        Map<String,Object> rspMap = courseService.getCourseInfoById(courseInfo.getId());
        logger.debug("out getCourseInfoById----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    
    /**
     * app课程预约
     */
    @ResponseBody
    @RequestMapping("/doCourseToBespeak")
    public ResultModel<Object> doCourseToBespeak(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in doCourseToBespeak----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseBespeak courseBespeak = (PtCourseBespeak) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseBespeak.class);
        //判空
        if(StringUtils.isBlank(courseBespeak.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约用户id不能为空");
        }
        if(courseBespeak.getCourseId()<=0){
        	logger.debug("out CourseId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约课程不能为空");
        }
        if(StringUtils.isBlank(courseBespeak.getPhoneNo())){
        	logger.debug("out PhoneNo----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预留电话不能为空");
        }
        if(StringUtils.isBlank(courseBespeak.getPersenName())){
        	logger.debug("out PersenName----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约人不能为空");
        }
        if(courseBespeak.getJoinNumber()<=0){
        	logger.debug("out JoinNumber----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"参加人数选择错误");
        }
        Map<String,Object> rspMap = courseService.doCourseToBespeak(courseBespeak);
        logger.debug("out doCourseToBespeak----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 通过预约id获取课程预约信息
     */
    @ResponseBody
    @RequestMapping("/getCourseBespeakById")
    public ResultModel<Object> getCourseBespeakById(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getCourseBespeakById----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseBespeak courseBespeak = (PtCourseBespeak) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseBespeak.class);
        //判空
        if(StringUtils.isBlank(courseBespeak.getId())){
        	logger.debug("out id----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约用户id不能为空");
        }
        Map<String,Object> rspMap = courseService.getCourseBespeakById(courseBespeak.getId());
        logger.debug("out getCourseBespeakById----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 取消预约或签到
     */
    @ResponseBody
    @RequestMapping("/cancelBespeak")
    public ResultModel<Object> cancelBespeak(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in cancelBespeak----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseBespeak courseBespeak = (PtCourseBespeak) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseBespeak.class);
        //判空
        if(StringUtils.isBlank(courseBespeak.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约用户id不能为空");
        }
        if(StringUtils.isBlank(courseBespeak.getId())){
        	logger.debug("out id----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约id不能为空");
        }
        if(courseBespeak.getBespeakState()!=2 && courseBespeak.getBespeakState()!=3){
        	logger.debug("out id----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"操作状态不能为空");
        }
        Map<String,Object> rspMap = courseService.cancelBespeak(courseBespeak);
        logger.debug("out cancelBespeak----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * app分页查询预约
     */
    @ResponseBody
    @RequestMapping("/listCourseBespeakForPage")
    public ResultModel<Object> listCourseBespeakForPage(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in listCourseBespeakForPage----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        //获取实体参数
        PtCourseBespeak courseBespeak = (PtCourseBespeak) JsonToEnetityUtil.jsonToObject(requestParam, PtCourseBespeak.class);
        //判空
        if(StringUtils.isBlank(courseBespeak.getUserId())){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"预约用户id不能为空");
        }
        courseBespeak.setStartNum((courseBespeak.getCurPage()-1)*courseBespeak.getPageSize());
        Map<String,Object> rspMap = courseService.listCourseBespeakForPage(courseBespeak);
        logger.debug("out listCourseBespeakForPage----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 查询有课程的近四天的日期
     */
    @ResponseBody
    @RequestMapping("/getCourseDayOfFour")
    public ResultModel<Object> getCourseDayOfFour(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
        logger.info("in getCourseDayOfFour----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        Map<String,Object> rspMap = courseService.getCourseDayOfFour();
        logger.debug("out getCourseDayOfFour----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 跑数据使用
     */
    @ResponseBody
    @RequestMapping("/selectPDateForTime")
    public ResultModel<Object> selectPDateForTime(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
    	JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String startTime = requestParam.getString("startTime");
        if(StringUtils.isBlank(startTime)){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"开始时间不能为空");
        }
        String endTime = requestParam.getString("endTime");
        if(StringUtils.isBlank(endTime)){
        	logger.debug("out UserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"结束时间不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        Map<String,Object> rspMap = courseService.selectPDateForTime(paramMap);
        return new ResultModel<Object>(rspMap);
    }
    /**
     * 通过userid和queue获取建档
     */
    @ResponseBody
    @RequestMapping("/getArchives")
    public ResultModel<Object> getArchives(HttpServletRequest request, @RequestBody String jsonStr) throws Exception {
    	JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String uesrId = requestParam.getString("userId");
        if (null == uesrId) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "userId不能为空！");
        }
        String queueId = requestParam.getString("queueId");
        if (null == queueId) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "queueId不能为空！");
        }
		//先查看 是否加入该租户队列
		Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",uesrId);
		ptMap.put("queueId",queueId);
		
		List<String> statulist = new ArrayList<String>();
		statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		ptMap.put("status", statulist);
		List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
		if(CollectionUtils.isEmpty(queueSchemeList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者建档流程信息不存在");
		}
		String tenantId = queueSchemeList.get(0).getTenantId();
		String ptSchemeId =  queueSchemeList.get(0).getId();
		ptMap.clear();
		ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
		ptMap.put("ptSchemeId",ptSchemeId);
		// 查询taskid
		List<PatientTask> taskList = patientTaskDao.select(ptMap);
		String taskId ="";
		if (!CollectionUtils.isEmpty(taskList)) {
			taskId = taskList.get(0).getId();
		}
		Map<String,Object> queueMap = new HashMap<String,Object>();
		queueMap.put("id", queueId);
		;
		ptMap.put("tenantId", tenantId);
        ptMap.put("groupType", Constants.TENANT_GROUP_TYPE_FOR_MULCENTER);
        ptMap.put("rootGroupId", followQueueDAO.selectById(queueMap).get(0).getDeptId());
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
        }
        ptMap.put("taskId", taskId);
        ptMap.put("queueId", queueId);
        Map<String, Object> retMap = patientService.qryPatientContentList(ptMap);
        Map<String, Object> questiones =JSONObject.parseObject(JSON.toJSONString(retMap.get("values")));
        
        return new ResultModel<Object>(questiones);
    }
}
